package com.rockgle.widget;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import com.rockgle.reader.Entry;
import com.rockgle.reader.PreferenceMonitor;
import com.rockgle.reader.R;
import com.rockgle.reader.SortedEntryList;

public class PostListAdapter extends BaseAdapter{
	
	/**
	 * @return the data
	 */
	public SortedEntryList getData() {
		return data;
	}
	/**
	 * @param data the data to set
	 */
	public void setData(SortedEntryList data) {
		this.data = data;
	}
	private SortedEntryList data;
	private LayoutInflater mInflater;
	private Context context;
	
	public PostListAdapter(Context context, SortedEntryList data){
		this.data = data;
		this.context = context;
		mInflater = LayoutInflater.from(context);
	}
	
	/**
	 * @return the context
	 */
	public Context getContext() {
		return context;
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getCount()
	 */
	@Override
	public int getCount() {
		return data.size();
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getItem(int)
	 */
	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getItemId(int)
	 */
	@Override
	public long getItemId(int position) {
		return position;
	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			
			convertView = mInflater.inflate(R.layout.list_item, null);
			
			holder = new ViewHolder();
			
			holder.title = (TextView) convertView.findViewById(R.id.listitemtitle);
            holder.updated = (TextView) convertView.findViewById(R.id.listitemdate);

            convertView.setTag(holder);	
        } else {
        	holder = (ViewHolder) convertView.getTag();
        }

		holder.title.setText(data.get(position).getTitle());

		StringBuilder text = new StringBuilder(data.get(position).getPublishedPrettyPrint());
		text.append(" por ");
		text.append(data.get(position).getAuthor());
		holder.updated.setText(text.toString());

        return convertView;

	}
	static class ViewHolder {
        TextView title;
        TextView updated;
    }
	
	public void clear(){
		data.clear();
		notifyDataSetChanged();
	}
	
	public void refresh(){
		if(PreferenceMonitor.getOnlyUnread()){
			SortedEntryList lista = new SortedEntryList();
			for (Entry entry: data){
				if (!entry.isRead()){
					lista.add(entry);
				}
			}
			data.clear();
			data.addAll(lista);
			notifyDataSetChanged();
			
		}
	}
}
